package com.gitee.fsadmin.common.util;

import com.gitee.fastmybatis.core.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.noear.solon.core.handle.Context;

import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * @author tanghc
 */
@Slf4j
public class RequestUtil {

    /**
     * 获取表单中的字段，请求类型是application/x-www-form-urlencoded
     *
     * @param request request
     * @return 返回字段内容
     */
    public static Map<String, String> getFormFields(Context request) {
        String query;
        try {
            InputStream inputStream = request.bodyAsStream();
            query = IOUtils.toString(inputStream, request.contentCharset());
        } catch (IOException e) {
            log.error("获取form参数失败", e);
            throw new RuntimeException("请求失败");
        }
        return parseQueryString(query);
    }

    public static Map<String, String> parseQueryString(String query) {
        if (StringUtils.isEmpty(query)) {
            return Collections.emptyMap();
        }
        query = StringUtil.trimLeadingCharacter(query, '?');
        String[] pairs = query.split("&");
        Map<String, String> form = new HashMap<>(pairs.length * 2);
        for (String pair : pairs) {
            String[] param = pair.split("=");
            String key = param[0];
            String value = null;
            try {
                value = URLDecoder.decode(param[1], "UTF-8");
            } catch (UnsupportedEncodingException e) {
                throw new RuntimeException(e);
            }
            form.put(key, value);
        }
        return form;
    }

    /**
     * 获取上传文件表单中的字段，排除query参数
     *
     * @param request request
     * @return 返回字段内容
     */
    public static Map<String, String> getMultipartFields(Context request) {
        Map<String, String> queryParams = parseQueryString(request.queryString());
        Map<String, String> uploadParams = new HashMap<>(16);
        Set<String> queryKeys = queryParams.keySet();
        request.paramMap().forEach((entry) -> {
            // 排除query param
            if (!queryKeys.contains(entry.getKey())) {
                uploadParams.put(entry.getKey(), entry.getFirstValue());
            }
        });
        return uploadParams;
    }

    /**
     * 获取客户端IP
     *
     * @param context request
     * @return 返回ip
     */
    public static String getIP(Context context) {
        return context.realIp();
    }
}
